package com.moss.system.service.impl;


import com.moss.common.domain.LoginUser;
import com.moss.common.domain.SysLogin;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.MD5Util;
import com.moss.common.util.RedisCache;
import com.moss.common.util.TokenUtil;

import com.moss.common.entity.SysUserEntity;
import com.moss.system.service.UserService;
import com.moss.system.service.LoginService;

import com.moss.system.service.PermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author gxcc3
 * @date: 2024/8/22 23:13
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    UserService userService;

    @Resource
    PermissionService permissionService;

    @Resource
    RedisCache redisCache;


    @Override
    public SysLogin login(SysUserEntity loginBody) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        SysUserEntity user = userService.selectUserByName(username);
        if (user == null){
            throw new ServiceException("用户不存在");
        }
        if (user.getStatus() == 0){
            throw new ServiceException("当前用户已停用");
        }
        String md5_salt = user.getMd5Salt();
        if (!user.getPassword().equals(MD5Util.getMd5(password,md5_salt))){
            throw new ServiceException("密码错误");
        }
        String token = TokenUtil.getToken(new LoginUser(user.getUserId(),user.getRealName(),user.getOrgId()));
//        String userId = user.getUser_id();
//        List<String> perms = userService.getUserPermsList(userId);
//        String permsKey = RedisConstants.USER_PERMS_KEY + token;
        //将token权限以json存储到redis
//        redisCache.setCacheObject(permsKey, JSONObject.toJSONString(perms), Constants.TOKEN_EXPIRATION, TimeUnit.SECONDS);
        return new SysLogin(user.getRealName(),token);
    }
}
